package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.business.domain.dto.SalesStatisticsDTO;
import com.ruoyi.business.mapper.GoodsMapper;
import com.ruoyi.business.mapper.SalesMapper;
import com.ruoyi.business.service.IStatisticsService;
import com.ruoyi.common.utils.DateUtils;

/**
 * 数据统计服务实现
 * 
 * @author ruoyi
 */
@Service
public class StatisticsServiceImpl implements IStatisticsService {

    @Autowired
    private SalesMapper salesMapper;
    
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 获取销售统计数据
     * 
     * @param userId 用户ID，若为null则获取所有数据
     * @return 销售统计数据
     */
    @Override
    public SalesStatisticsDTO getSalesStatistics(Long userId) {
        SalesStatisticsDTO statistics = new SalesStatisticsDTO();
        
        // 获取今日日期
        Date today = DateUtils.getNowDate();
        Date startOfToday = DateUtils.getBeginOfDay(today);
        Date endOfToday = DateUtils.getEndOfDay(today);
        
        // 获取本月起止日期
        Date startOfMonth = DateUtils.getBeginOfMonth(today);
        Date endOfMonth = DateUtils.getEndOfMonth(today);
        
        // 获取今日销售额
        BigDecimal todaySales = salesMapper.getSumActualPaymentByDateRange(startOfToday, endOfToday, userId);
        if (todaySales != null) {
            statistics.setTodaySales(todaySales);
        }
        
        // 获取本月销售额
        BigDecimal monthlySales = salesMapper.getSumActualPaymentByDateRange(startOfMonth, endOfMonth, userId);
        if (monthlySales != null) {
            statistics.setMonthlySales(monthlySales);
        }
        
        // 获取本月利润
        BigDecimal monthlyProfit = salesMapper.getMonthlyProfit(startOfMonth, endOfMonth, userId);
        if (monthlyProfit != null) {
            statistics.setMonthlyProfit(monthlyProfit);
        }
        
        // 获取库存总量
        BigDecimal inventoryCount = goodsMapper.getTotalStockQuantity(userId);
        if (inventoryCount != null) {
            statistics.setInventoryCount(inventoryCount);
        }
        
        return statistics;
    }
} 